/*
 * @Author: wys
 * @Date: 2021-06-30 09:30:51
 * @LastEditors: wys
 * @LastEditTime: 2021-06-30 20:09:15
 * @Description: 跳过选择sku的弹窗选择默认sku，直接下单，go_order_pay(goods)传入商品goods，
 */
import { getOrderState } from '@/utils/common'
import { getUserLevel } from '@/utils/common'
import { parseTime, inputCheckNumber, formatUrlParam, throttle, getQueryString } from '@/utils/tools'
import { toFunctionDetail } from '@/utils/navigateTo'
import { navigateToMiniProgram, toMpHomePage, pageNavigateBack } from '@/utils/navigateTo'
var myMixin = {
  data() {
    return {
      allData:"",
      goods:"",
      select_sku_good:"",
      userCoupon:1,//是否使用优惠券
    }
  },
  created(){
  },
  methods: {
    //直接下单跳转支付页
    go_order_pay({goods,userCoupon=1}){
      this.userCoupon=userCoupon;//是否使用优惠券
      if(goods){
        this.getGoodDetail(goods);
      }
    },
    //获取商品详情
    async getGoodDetail(goods){
      const subForm = {
        goods_id: goods.goods_id,
        from_type: this.$utils.isNull(goods.from_type)?'1':goods.from_type,
        activity_id: goods.activity_id,
        goods_type: this.$utils.isNull(goods.type)?'1':goods.type,
        pack_type: this.$utils.isNull(goods.pack_type)?'2':goods.pack_type
      }
      // const subForm = {
      //   goods_id: 'A0F3A34158987070FAA0358D1BDBFB32',
      //   from_type: '1',
      //   activity_id: '',
      //   goods_type: 2,
      //   pack_type: '2'
      // }
      let res = await this.$api.goodsApi.goodsDetail(subForm);
      if(res.code==0){
        this.allData = res.data;
        this.goods = res.data.goods;
        this.select_sku_good=this.get_sku_item(this.goods,res.data);//获取商品规格
        console.log(this.select_sku_good);
        //跳转下单页
        if(this.select_sku_good){
          this.toOrderDetail(this.select_sku_good);
        }else{
          this.$msg('暂未获取到商品信息，请稍后重试');
        }
      }
    },
    //获取商品规格
    get_sku_item(goods,res){
      let goods_data;
      //套餐
      if(goods.type==2){
        let packageList=[];//套餐选择
        let presentList=[];//赠品选择
        let selectedSkuItem;
        /* 套餐选择 */
        let orignPackList = goods.goods_pack.pack.map((item, index) => {
          item.selfId = item.goods_id + index
          // item.properties_name = '请选择'
          if (item.sku_list) {
            try {
              item.sku_list[0].selectText = item.sku_list[0].properties_name.split(';').reduce((a, b) => a.split(':')[1] + '; ' + b.split(':')[1])
            } catch (e) {
              console.log('e', e)
            }
            this.changePackageSkuItem(item.sku_list[0], item, 'package')
            selectedSkuItem=item.sku_list[0];
          } else {
            this.changePackageSkuItem(null, item, 'package')
            selectedSkuItem=null;
          }
          //套餐是否全选，否则选第一个
          const selectAll = goods.goods_pack.pack.length === goods.goods_pack.pack_selected_num;
          if ((selectAll || goods.pack_type === 1) && Number(item.status === 3)) {
            item.unable = true
            packageList.push(item)
          }else if(index==0){
            item.unable = true
            packageList.push(item)
          }
          // if (Number(item.status) === 3) {//判断状态
          //   item.unable = true
          //   packageList.push(item)
          // }
          return item
        })
        /* 赠品选择*/
        if (goods.goods_pack && goods.goods_pack.present.length) {
          let orignPresentList = goods.goods_pack.present.map((item, index) => {
            item.selfId = item.goods_id + index
            if (item.sku_list) {
              try {
                item.sku_list[0].selectText = item.sku_list[0].properties_name.split(';').reduce((a, b) => a.split(':')[1] + '; ' + b.split(':')[1])
              } catch (e) {
                console.log('e', e)
              }
              this.changePackageSkuItem(item.sku_list[0], item, 'present');
              selectedSkuItem=item.sku_list[0];
            } else {
              this.changePackageSkuItem(null, item, 'present');
              selectedSkuItem=null;
            }
            //赠品是否全选，否则选第一个
            const presentAll = goods.goods_pack.present.length === goods.goods_pack.present_selected_num;
            if (presentAll) {
              item.unable = true
              presentList.push(item)
            }else if(index==0){
              item.unable = true
              presentList.push(item)
            }
            // item.unable = true
            // presentList.push(item)
            return item
          })
        }
        goods_data = {
          selectedSkuItem: selectedSkuItem,
          count: 1,
          maskType: "package",
          packageList: packageList,
          presentList: presentList,
          buyType: "buyBtn",
        }
      }
      //组合套餐
      else if(goods.type==4){
        if (res.goods.type === 4) {
          // 组合套餐数据变更，取 rsp_data_list
          // 主体下架的对应处理
          if (res.goods.status === 5) {
            res.rsp_data_list.map(item => {
              item.goods.status = 5
              return item
            })
          }
          // 会员层级价区间赋值
          let priceArea = [] // 价格区间
          const vipArr = [] // 会员价格
          const otherArr = [] // 会员价格
          const comboSkulist = []//规格列表
          res.rsp_data_list.map(item => {
            // 价格区间 设置
            vipArr.push(item.goods.vip_price)
            otherArr.push(item.goods[getUserLevel()])
            // 判断是否可买
            let enableBuy = false
            if (item.goods.status === 3) {
              enableBuy = true
              // 只要套餐中有一个不可购买
              item.goods.goods_pack.pack.map(item => {
                if (item.status !== 3) {
                  enableBuy = false
                }
              })
            }
            // 规格列表
            comboSkulist.push({
              ...item.goods,
              enable: enableBuy
            })
          })
          if (!this.token) {
            priceArea = [Math.min(...vipArr), Math.max(...vipArr)]
          }
          if (goods.from_type === 9) {
            priceArea = [Math.min(...otherArr), Math.max(...otherArr)]
          } else {
            priceArea = [Math.min(...vipArr), Math.max(...vipArr)]
          }
          res.goods.priceArea = priceArea;
          res.goods.ComboPriceMin = priceArea[0];
          res.goods.ComboPriceMax = priceArea[1];
          res.goods.comboSkulist = comboSkulist;
        }
        let selectedSkuItem=res.goods.comboSkulist[0];
        selectedSkuItem.checked = !selectedSkuItem.checked
        selectedSkuItem.selectText = selectedSkuItem.title
        selectedSkuItem.order_limit = selectedSkuItem.goods_pack.limit_num
        selectedSkuItem.min_num = selectedSkuItem.goods_pack.min_num
        selectedSkuItem.goods_pic = selectedSkuItem.pic
        selectedSkuItem.goods_pack.pack.map(item => {
          item.selectedSkuItem = item.sku_list[0]
        })
        selectedSkuItem.goods_pack.present.map(item => {
          item.selectedSkuItem = item.sku_list[0]
        })
        goods_data={
          goods: selectedSkuItem,
          packageList: selectedSkuItem.goods_pack.pack,
          presentList: selectedSkuItem.goods_pack.present,
          selectedSkuItem: selectedSkuItem.goods_pack.pack[0].sku_list[0],
          count: 1,
          maskType: "combo",
          buyType: 'buyBtn'
        }
      }
      //单品,选择第一个
      else{
        let selectedSkuItem=goods.sku_list[0];
        let sku_arr=[];
        selectedSkuItem.properties_name.split(";").forEach(item=>{
          sku_arr.push(item.split(":")[1]);
        })
        selectedSkuItem.selectText=sku_arr.join(";");
        goods_data = {
          selectedSkuItem: selectedSkuItem,
          count: 1,
          maskType: 'singleGoods',
          buyType: 'buyBtn'
        }
      }
      return goods_data;
    },
    changePackageSkuItem(item, ringe, type) {
      if (ringe) {
        this.$set(ringe, 'selectedSkuItem', item)
        if (item) {
          this.$set(ringe, 'properties_name', item.selectText)
          this.$set(ringe, 'num', item.package_goods_number)
        } else {
          this.$set(ringe, 'properties_name', '请选择')
          this.$set(ringe, 'num', ringe.sku_list[0] ? ringe.sku_list[0].package_goods_number : '0')
        }
        this.$set(ringe, 'checkBorder', false)
      }
    },
    //跳转下单页
    async toOrderDetail(buyObj) {
      let data = {
        goods_id: this.goods.goods_id,
        goods_type: this.goods.type * 1 === 0 ? '1' : this.goods.type + '',
        sku_code: '',
        activity_id: this.goods.activity_id,
        pack_list: [],
        pack_type: this.goods.pack_type * 1 === 0 ? 2 : this.goods.pack_type,
        present_list: [],
        num: buyObj.count,
        from_type: this.goods.from_type * 1 === 0 ? '1' : this.allData.full_cut_id ? 24 : this.goods.from_type + ''
      }
      // 如果是组合套餐则为 data 重新赋值
      if (this.goods.type === 4) {
        data = {
          goods_id: buyObj.goods.goods_id,
          goods_type: buyObj.goods.type * 1 === 0 ? '1' : buyObj.goods.type + '',
          sku_code: '',
          activity_id: buyObj.goods.activity_id,
          pack_list: [],
          pack_type: buyObj.goods.pack_type * 1 === 0 ? 2 : buyObj.goods.pack_type,
          present_list: [],
          num: buyObj.count,
          from_type: buyObj.goods.from_type * 1 === 0 ? '1' : this.allData.full_cut_id ? 24 : buyObj.goods.from_type + ''
        }
      }
      if (buyObj.isDefine) {
        data.activity_id = buyObj.activity_id
        data.from_type = this.allData.full_cut_id ? 24 : buyObj.from_type
      }
      if (buyObj.maskType === 'package' || buyObj.maskType === 'combo') {
        buyObj.packageList.forEach(element => {
          data.pack_list.push({
            sku_code: element.selectedSkuItem.sku_code,
            num: element.selectedSkuItem.package_goods_number,
            activity_id: element.selectedSkuItem.activity_id,
            from_type: element.selectedSkuItem.from_type
          })
        })
      } else if (buyObj.maskType !== 'bonusGift') {
        data.sku_code = buyObj.selectedSkuItem.sku_code
      }
      if (buyObj.presentList && buyObj.presentList.length) {
        const presentSku = []
        buyObj.presentList.forEach(element => {
          presentSku.push({
            sku_code: element.selectedSkuItem.sku_code,
            num: element.selectedSkuItem.package_goods_number,
            activity_id: element.selectedSkuItem.activity_id,
            from_type: element.selectedSkuItem.from_type
          })
        })
        data.present_list = presentSku
      }
      // 校验购买数量防止传参无意义报错
      const numCheckResult = inputCheckNumber(buyObj.count)
      if (!numCheckResult) {
        return
      }
      data.buyData = JSON.stringify([data])
      if (this.goods.from_type === 13) {
        const goodsCanBuy = await this.$api.orderApi.goodsValidate({
          num: data.num,
          pack_type: data.pack_type,
          activity_id: data.activity_id,
          goods_type: data.goods_type,
          goods_id: data.goods_id,
          from_type: data.from_type
        })
        if (goodsCanBuy.code) {
          return
        }
      }
      // 判断是否使用优惠券
      let userCoupon = this.userCoupon;
      // if (this.showCoupon) {
      //   userCoupon = 1
      // } else {
      //   if (this.goods.type === 4) {
      //     userCoupon = 1
      //   }
      // }
      const settleData = {
        is_used_coupon: userCoupon,
        shopping_list: data.buyData,
        shipping_address_id: ''
      }
      const res = await this.$api.orderApi.orderSettle(settleData)
      this.$store.dispatch('setGoodsTemp', {
        shopping_list: data.buyData,
        data: res.data,
        settleData
      })
      if (res.code || !res || !res.data) {
        return
      }
      // uni.setStorageSync('preseat', '商品详情')
      // uni.setStorageSync('firstseat', uni.getStorageSync('firstseat'))
      this.$navigateTo('/pagesOrder/orderCheck/index')
    },
  }
}
export default myMixin;